import org.junit.Before;
import org.junit.Test;

import java.util.LinkedList;
import java.util.List;

import static org.mockito.Mockito.*;


public class ThrowException {

    LinkedList mockedList = null;

    @Before
    public void before() {
        mockedList = mock(LinkedList.class);
    }

    @Test
    public void testVerify() {
//        mockedList.add("once");
        verify(mockedList).add("once");

    }

    //测试方法是否被执行过1次
    @Test
    public void testVerify2() {
        // 调用add一次
        mockedList.add("once");
        // 下面两个写法验证效果一样，均验证add方法是否被调用了一次
        verify(mockedList).add("once");
        verify(mockedList, times(1)).add("once");

    }


    @Test
    public void testActionBeDone() {
        //验证方法是否别吊用过 使用verify
        // mock creation 创建mock对象
        List mockedList = mock(List.class);

        //using mock object 使用mock对象
        mockedList.add("one");
        mockedList.clear();

        //verification 验证
        //验证方法调用(是否调用了get(0))
//        verify(list).get(0);
        verify(mockedList).add("one");
        verify(mockedList).clear();

    }

    //测试 方法是否被执行了几次
    @Test
    public void testActionTimes() {
        mockedList.add("once");

        mockedList.add("twice");
        mockedList.add("twice");

        mockedList.add("three times");
        mockedList.add("three times");
        mockedList.add("three times");

        //following two verifications work exactly the same - times(1) is used by default
        // 下面的两个验证函数效果一样,因为verify默认验证的就是times(1)
        verify(mockedList).add("once");
        verify(mockedList, times(1)).add("once");

        //exact number of invocations verification
        // 验证具体的执行次数
        verify(mockedList, times(2)).add("twice");
        verify(mockedList, times(3)).add("three times");

        //verification using never(). never() is an alias to times(0)
        // 使用never()进行验证,never相当于times(0)
        verify(mockedList, never()).add("never happened");

        //verification using atLeast()/atMost()
        // 使用atLeast()/atMost()
        verify(mockedList, atLeastOnce()).add("three times");
        verify(mockedList, atLeast(2)).add("five times");
        verify(mockedList, atMost(5)).add("three times");

    }


    //执行clear方法抛异常
    @Test
    public void testThrowEx() {
        doThrow(new RuntimeException()).when(mockedList).clear();
        mockedList.clear();
    }


    //anyInt参数方法
    @Test
    public void testParam() {
        when(mockedList.get(anyInt())).thenReturn("element");
        mockedList.clear();
    }

}
